package cc.sheji.controller.admin;

import cc.sheji.Service.UserService;
import cc.sheji.domain.*;
import io.lettuce.core.RedisConnectionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;

@Validated
@RestController
@RequestMapping(value = "/admin/v1/user")
public class AdminUserController {

    @Autowired
    UserService userService;


    @GetMapping("total")
    public JsonResult total() throws InterruptedException {
        return JsonResult.Success(userService.total());
    }


    @GetMapping("/{id}")
    public JsonResult get(@PathVariable Long id) {

        return JsonResult.Success(userService.get(id));
    }

    @GetMapping()
    public JsonResult get(UserQueryCriteria criteria, Pageable pageable) throws InterruptedException {
        return JsonResult.Success(userService.list(criteria, pageable));
    }



    @PostMapping("addCoin")
    public JsonResult addCoin(@RequestBody  AddCoin addCoin) {

        return JsonResult.Success(userService.addCoin(addCoin.getUserId(),addCoin));
    }



    @PostMapping("register")
    public JsonResult create(@RequestBody @Validated(User.AddeGroup.class) User user) {

        user.setId(null);
        user.setAvator("https://img0.baidu.com/it/u=4060770951,4069855872&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500");
        try {
            return JsonResult.Success(userService.create(user));
        }catch ( RedisConnectionException e){
            e.printStackTrace();
            return new JsonResult(ErrorCode.ExistUserException, "redis");
        }

        catch (DataIntegrityViolationException e) {
            e.printStackTrace();
            return new JsonResult(ErrorCode.ExistUserException, "用户名已存在");
        }
    }

    @PutMapping("/{id}")
    public JsonResult update(@PathVariable(name = "id") Long id, @Valid User user) {

        user.setId(id);
       // user.setLevel(0);
        return JsonResult.Success(userService.update(user));
    }

}
